//
//  PowerDetailController.swift
//  SCA
//
//  Created by tjun on 2025/9/13.
//

import UIKit
import SnapKit


class PowerDetailController: BaseController {
    
    let pool: String
    let poolName: String
    let poolIconUrl: String

    private let powerCircleView = PowerCircleView()
    private let powerValueView = PowerValueView()

    private var lastAlpha: CGFloat = -1 // 记录上次的透明度

    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.backgroundColor = AppStyle.color.background
        tableView.rowHeight = 224
        tableView.contentInsetAdjustmentBehavior = .never;
        tableView.register(PowerDetailCell.self, forCellReuseIdentifier: PowerDetailCell.identifier)
        tableView.estimatedRowHeight = 0;
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: tabBarSafeBottomMargin, right: 0)
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        return tableView
    }()
    
    init (pool: String, poolName: String, poolIconUrl: String) {
        self.pool = pool
        self.poolName = poolName
        self.poolIconUrl = poolIconUrl
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var datas: [PowerDetailModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationBar.backgroundColor = .clear

        let headerView = UIView(frame: CGRectMake(0, 0, screenWidth, 200))
        let backgroundImageView = UIImageView().addTo(headerView)
        backgroundImageView.image = UIImage(fileName: "powerDetail_bg")
        backgroundImageView.contentMode = .scaleAspectFill
        backgroundImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
        }
   
        powerCircleView.addTo(headerView)
        powerCircleView.setCenterText(top: "算力".localizedString, value: "0.00", unit: "G")

        powerCircleView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(50)
            make.width.equalTo(146.scaled)
            make.top.equalTo(backgroundImageView.snp.bottom).offset(20)
            make.height.equalTo(146.scaled)
        }
        
        powerValueView.addTo(headerView)
        powerValueView.snp.makeConstraints { make in
            make.left.equalTo(powerCircleView.snp.right).offset(50)
            make.right.equalTo(-AppStyle.margin.left)
            make.top.equalTo(powerCircleView)
            make.height.equalTo(powerCircleView)
        }
        
        headerView.setNeedsLayout()
        headerView.layoutIfNeeded()
        headerView.frame = CGRectMake(0, 0, screenWidth, powerCircleView.maxY + 20)
        
        tableView.tableHeaderView = headerView
        tableView.addTo(view)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let coinImageView = UIImageView().addTo(headerView)
        coinImageView.setImage(url: poolIconUrl)
        coinImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(navBarHeight)
            make.width.height.equalTo(90)
        }
        
        let nemeLabel = UILabel(text: poolName, font: UIFontSemiboldMake(18), textColor: .white).addTo(headerView)
        nemeLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(coinImageView.snp.bottom).offset(8)
        }
        
        let earningsRecordButton = UIButton(image: UIImage(named: "extractRecords"), target: self, action: #selector(earningsRecordButtonTapped)).addTo(headerView)
        earningsRecordButton.snp.makeConstraints { make in
            make.top.equalTo(nemeLabel.snp.bottom).offset(20)
            make.right.equalTo(-AppStyle.margin.left)
            make.width.height.equalTo(30)
        }
        
        loadData()
    }
    
    private func loadData() {
        ComputingPowerService.loadPowerDetailData(pool: pool) { models, total in
            self.datas.append(contentsOf: models)
            self.tableView.reloadData()
        } failure: { error in
        
        }
        ComputingPowerService.loadPoolPowerOverviewData(pool: pool) { info in
            self.powerCircleView.powerInfo = info
            self.powerValueView.powerInfo = info
        }
    }
    
    @objc func earningsRecordButtonTapped() {
        let earningsRecordController = EarningsRecordController(pool: pool)
        navigationController?.pushViewController(earningsRecordController, animated: true)
    }
    
}

extension PowerDetailController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PowerDetailCell.identifier, for: indexPath) as! PowerDetailCell
        cell.model = datas[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = datas[indexPath.row]
        
        let castingEarningsRecordController = CastingEarningsRecordController(pool: model.pool, Id: model.Id)
        navigationController?.pushViewController(castingEarningsRecordController, animated: true)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y
        let headerHeight: CGFloat = 150
        let alpha = min(1, max(0, offsetY / headerHeight))
        
        if abs(alpha - lastAlpha) > 0.001 {
            navigationBar.backgroundColor = AppStyle.color.background.withAlphaComponent(alpha)
            lastAlpha = alpha
        }
    }
}
